<script setup lang="ts">
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import { nextTick, ref } from 'vue';
import { ApiRole } from '../../api';
import { useRoleStore } from '../../store';
import { storeToRefs } from 'pinia';


const {list}=storeToRefs(useRoleStore())
const show=ref<boolean>(false)
const model=ref<API.Role.Update>({role_name:"", role_id:0})
const formRef=ref<FormInstance|null>(null)
const emits=defineEmits<{(name:'save',model:API.Role.Add):void}>()

const rules:FormRules={
    role_name:[{required:true,message:"请输入角色名称",trigger:"blur"},
        {min:2,max:10,message:"长度在2到10个字符",trigger:"blur"},
        //@ts-ignore
        {validator:(rule,value,cb)=>{
            if(list.value.some(item=>item.role_name===value)){
                cb(new Error("角色名已存在"))
            }else{
                cb()
            }
        }}
    ]
}
const save=async()=>{
    formRef.value?.validate()
    await ApiRole.add(model.value)
    emits('save',model.value)
    ElMessage.success("添加成功")
    show.value=false
}
const cancel=async()=>{
    await ElMessageBox.confirm("取消数据会丢失哦？", "提示", { type: "warning" });
    show.value=false
}
defineExpose({
    begin:(data:API.Role.Update)=>{  
        formRef.value?.resetFields()
        model.value.role_id=data.role_id
        model.value.role_name=data.role_name
      
        nextTick(()=> show.value=true)
    }
})
</script>

<template>
 <el-dialog title="角色编辑" width="500px" v-model="show">
    <el-form ref="formRef" :model="model" label-width="80px" :prop="rules">
        <el-form-item label="角色名称" prop="role_name">
            <el-input v-model="model.role_name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
    </el-form>
     <div slot="footer">
         <el-button @click="cancel">取 消</el-button>
         <el-button type="primary" @click="save">确 定</el-button>
     </div>
 </el-dialog>
</template>

<style scoped lang="scss">

</style>